import axios from 'axios'
import { useAuthStore } from '../stores/auth'

// Compose baseURL with '/api' path based on env host
const API_HOST = (import.meta.env.VITE_API_TARGET || '').replace(/\/+$/, '')
const instance = axios.create({
  baseURL: `${API_HOST}/api`,
  timeout: 15000
})

instance.interceptors.request.use((config) => {
  const auth = useAuthStore()
  if (auth.token) {
    config.headers.Authorization = `Bearer ${auth.token}`
  }
  return config
})

instance.interceptors.response.use(
  (resp) => {
    const data = resp?.data as any
    try {
      // 统一前端成功判断：将后端成功码（>0，例如1）规范化为 code=0
      if (data && typeof data === 'object' && 'code' in data) {
        const code = data.code
        if (typeof code === 'number' && code > 0) {
          resp.data = { ...data, code: 0 }
        }
      }
    } catch {
      // no-op
    }
    return resp
  },
  (error) => {
    // 处理401未授权错误
    if (error?.response?.status === 401) {
      const auth = useAuthStore()
      auth.logout()
      // 如果当前不在登录页面，则跳转到登录页面
      if (window.location.pathname !== '/login') {
        window.location.href = '/login'
      }
    }
    
    const msg = error?.response?.data?.message || error?.message || '请求失败'
    return Promise.reject(new Error(msg))
  }
)

export default instance
